package org.txazo.blog.commons.parser;

import java.io.IOException;
import java.util.Map;

import org.txazo.blog.commons.prop.ClassPathProperties;
import org.txazo.blog.commons.prop.Properties;

/**
 * ShellParser
 * 
 * @author Tu XiaoZhou
 * @since 2013-10-22
 * 
 */
public class ShellParser extends AbstractParser {

	private int comm = 0;
	private int awk = 0;

	private static final int SPAN_TYPE_COM = 1;
	private static final int SPAN_TYPE_KWD = 2;

	private static String SPAN_SHELL_COM = "<span class=\"shell-com\">";
	private static String SPAN_SHELL_KWD = "<span class=\"shell-kwd\">";
	private static String SPAN_END = "</span>";

	private static String conditionKeyWords = "if^then^elif^else^fi^for^do^done^while";
	private static Map<String, String> commandMap = null;

	static {
		Properties properties = new ClassPathProperties("shell.properties");
		commandMap = properties.load();
	}

	public ShellParser(String input, String output) {
		super(input, output);
	}

	@Override
	public void parse(String line) throws IOException {
		if (line.startsWith("#")) {
			write(line, SPAN_TYPE_COM);
		} else {
			String word = null;
			String[] words = line.split(" ");
			for (int i = 0; i < words.length; i++) {
				word = words[i];
				if (i == 0) {
					if (commandMap.get(word) != null) {
						write(word, SPAN_TYPE_KWD);
					} else {
						write(word);
					}
				} else {
					write(" ");
					write(word);
				}
			}
		}
	}

	private void write(String str) throws IOException {
		writer.write(str);
	}

	private void write(String str, int type) throws IOException {
		if (type == SPAN_TYPE_COM) {
			writer.write(SPAN_SHELL_COM + str + SPAN_END);
		} else if (type == SPAN_TYPE_KWD) {
			writer.write(SPAN_SHELL_KWD + str + SPAN_END);
		}
	}

	public static void main(String[] args) {
		Parser parser = ParserFactory.getParser("D:/search-id-gz.sh",
				"D:/zshell/2.html", ParserFactory.PARSER_TYPE_SHELL);
		parser.parse();
	}

}
